package com.shuqi.model.database;

import java.util.ArrayList;
import java.util.List;

import net.sqlcipher.database.SQLiteDatabase;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;

import com.shuqi.common.Constant;
import com.shuqi.common.utils.Log4an;
import com.shuqi.database.model.BookInfo;

/**
 * 页面缓存
 * 
 * @author zhangpeng
 * 
 */
public class PageCacheHelper {
    private static String TAG = "PageCacheHelper";
    private static String PAGE_BOOKSEARCH = "BookSearch";// 搜索页
    private static String PAGE_BOOKSQUARE = "BookSquare";// 书城页
    private static String PAGE_BOOKRECOMMEND = "BookRecommend";// 推荐页
    private static String BOOKSEARCH_CHILD_RANK = "rank";// 搜索排行
    private static String BOOKSEARCH_CHILD_RECOMMEND = "recommend";// 搜索推荐
    public static String BOOKSEARCH_CHILD_CURPAGE = "curpage";// 搜索联想词当页

    public static String BOOKSEARCH_CHILD_CUR_SEAECHWORD = "searchword";// 搜索联想词
    private static String BOOKSEARCH_CHILD_RECOMMEND_BOOKINFO = "bookInfo";// 搜索推荐书籍信息
    private static String BOOKSEARCH_CHILD_RECOMMEND_BOOK_LABEL = "label";// 搜索推荐书籍信息
    private static String BOOKSEARCH_CHILD_RANK_BOOK_INFO = "bookInfo";// 搜索排行书籍信息

    private static String BOOKSQUARE_CHILD_RECOMMEND = "recommend";// 书城推荐
    private static String BOOKSQUARE_CHILD_RECOMMEND_IMGS = "imgs";// 书城推荐导航图
    private static String BOOKSQUARE_CHILD_RECOMMEND_BOOKINFO = "bookInfo";// 书城推荐书籍

    private static String BOOKSQUARE_CHILD_RANK = "rank";// 书城排行
    private static String BOOKSQUARE_CHILD_RANK_BOOKINFO = "bookInfo";// 书城排行书籍
    private static String BOOKSQUARE_CHILD_RANK_BOOKLABEL = "label";// 书城排行标签

    private static String BOOKSQUARE_CHILD_SORT = "sort";// 书城分类
    private static String BOOKSQUARE_CHILD_SORT_BOOKINFO = "bookInfo";// 书城分类详情

    private static String BOOKSQUARE_CHILD_FREE = "free";// 书城限免
    private static String BOOKSQUARE_CHILD_FREE_BOOKINFO = "bookInfo";// 书城限免书籍信息

    private static String BOOKRCOMMEND_CHILD_ELLE = "recommendMan";// 推荐男频
    private static String BOOKRCOMMEND_CHILD_WOMEN = "recommendWomen";// 推荐女频
    private static String BOOKRCOMMEND_CHILD_ELLE_INFO = "recommendManInfo";// 推荐男频书籍信息
    private static String BOOKRCOMMEND_CHILD_WOMEN_INFO = "recommendWomenInfo";// 推荐女频书籍信息

    /***************************** 推荐页面相关缓存 *********************/
    /**
     * 获取推荐页男频书籍信息
     * 
     * @param context
     * @param uid
     * @return
     */
    public static List<BookInfo> getRecommendManBookInfo(Context context, String uid) {
        List<BookInfo> list =
                getPageCacheInfo(context, uid, PAGE_BOOKRECOMMEND, BOOKRCOMMEND_CHILD_ELLE,
                        BOOKRCOMMEND_CHILD_ELLE_INFO);
        return list;
    }

    /**
     * 添加推荐页男频书籍信息
     * 
     * @param context
     * @param uid
     * @param list
     * @return
     */
    public static void addRecommendManBookInfo(Context context, String uid, List<BookInfo> list) {
        if (list == null) {
            Log4an.e(TAG, "添加书城推荐页书籍信息 list is null");
            return;
        }
        addPageCacheInfo(context, uid, PAGE_BOOKRECOMMEND, BOOKRCOMMEND_CHILD_ELLE,
                BOOKRCOMMEND_CHILD_ELLE_INFO, list);
    }

    /**
     * 获取推荐页女频书籍信息
     * 
     * @param context
     * @param uid
     * @return
     */
    public static List<BookInfo> getRecommendWomenBookInfo(Context context, String uid) {
        List<BookInfo> list =
                getPageCacheInfo(context, uid, PAGE_BOOKRECOMMEND, BOOKRCOMMEND_CHILD_WOMEN,
                        BOOKRCOMMEND_CHILD_WOMEN_INFO);
        return list;
    }

    /**
     * 添加推荐页女频书籍信息
     * 
     * @param context
     * @param uid
     * @param list
     * @return
     */
    public static void addRecommendWomenBookInfo(Context context, String uid, List<BookInfo> list) {
        if (list == null) {
            Log4an.e(TAG, "添加书城推荐页书籍信息 list is null");
            return;
        }
        addPageCacheInfo(context, uid, PAGE_BOOKRECOMMEND, BOOKRCOMMEND_CHILD_WOMEN,
                BOOKRCOMMEND_CHILD_WOMEN_INFO, list);
    }

    /***************************** 搜索页面相关缓存 *********************/

    /**
     * 清楚搜索联想词信息
     */
    public static void clearSearchWordInfo(Context context, String uid) {
        delPageCacheInfo(context, uid, PAGE_BOOKSEARCH, BOOKSEARCH_CHILD_CURPAGE,
                BOOKSEARCH_CHILD_CUR_SEAECHWORD);
    }

    /**
     * 获取搜索联想词信息
     * 
     * @param context
     * @param uid
     * @return
     */
    public static List<String> getSearchWordInfo(Context context, String uid) {
        List<BookInfo> list =
                getPageCacheInfo(context, uid, PAGE_BOOKSEARCH, BOOKSEARCH_CHILD_CURPAGE,
                        BOOKSEARCH_CHILD_CUR_SEAECHWORD);
        ArrayList<String> list2 = new ArrayList<String>();
        if (list != null && list.size() > 0) {
            for (int i = list.size() - 1; i >= 0; i--) {
                list2.add(list.get(i).getBookName());
            }
        }
        return list2;
    }

    /**
     * 添加搜索联想词信息
     * 
     * @param context
     * @param uid
     * 
     */
    public static void addSearchWordInfo(Context context, String uid, String word) {
        Log4an.e(TAG, "uid:" + uid + ",word:" + word);
        if (word == null && "".equals(word)) {
            Log4an.e(TAG, "添加搜索联想词信息 list is null");
            return;
        }
        List<BookInfo> newList = new ArrayList<BookInfo>();

        List<BookInfo> list =
                getPageCacheInfo(context, uid, PAGE_BOOKSEARCH, BOOKSEARCH_CHILD_CURPAGE,
                        BOOKSEARCH_CHILD_CUR_SEAECHWORD);

        BookInfo newInfo = new BookInfo();
        newInfo.setBookName(word);

        boolean isExsit = false;
        if (list != null) {
            for (BookInfo info : list) {
                if (info.getBookName().equals(word)) {
                    isExsit = true;
                    break;
                }
            }

            if (isExsit) {
                for (BookInfo info : list) {
                    if (!info.getBookName().equals(word)) {
                        newList.add(info);
                    }
                }
            } else {
                // 多于10个，则移除最后一个；如果10个里面已经存在，则剔除上一个重复的
                if (list.size() > 10) {
                    int i = 0;
                    for (BookInfo info : list) {
                        if (i != 0) {
                            newList.add(info);
                        }
                        i++;
                    }
                } else {
                    for (BookInfo info : list) {
                        newList.add(info);
                    }
                }
            }
        }

        newList.add(newInfo);

        addPageCacheInfo(context, uid, PAGE_BOOKSEARCH, BOOKSEARCH_CHILD_CURPAGE,
                BOOKSEARCH_CHILD_CUR_SEAECHWORD, newList);

    }

    /**
     * 获取搜索推荐书籍信息
     * 
     * @param context
     * @param uid
     * @return
     */
    public static List<BookInfo> getSearchRecommendBookInfo(Context context, String uid) {
        List<BookInfo> list =
                getPageCacheInfo(context, uid, PAGE_BOOKSEARCH, BOOKSEARCH_CHILD_RECOMMEND,
                        BOOKSEARCH_CHILD_RECOMMEND_BOOKINFO);
        return list;
    }

    /**
     * 添加或替换搜索推荐书籍信息
     * 
     * @param context
     * @param uid
     * @param list
     */
    public static void addSearchRecommendBookInfo(Context context, String uid, List<BookInfo> list) {
        if (list == null) {
            Log4an.e(TAG, "添加或替换搜索推荐书籍信息 list is null");
            return;
        }
        addPageCacheInfo(context, uid, PAGE_BOOKSEARCH, BOOKSEARCH_CHILD_RECOMMEND,
                BOOKSEARCH_CHILD_RECOMMEND_BOOKINFO, list);
    }

    /**
     * 获取搜索推荐标签信息
     * 
     * @param context
     * @param uid
     * @return
     */
    public static List<BookInfo> getSearchRecommendLabel(Context context, String uid) {
        List<BookInfo> list =
                getPageCacheInfo(context, uid, PAGE_BOOKSEARCH, BOOKSEARCH_CHILD_RECOMMEND,
                        BOOKSEARCH_CHILD_RECOMMEND_BOOK_LABEL);
        return list;
    }

    /**
     * 添加搜索推荐标签信息
     * 
     * @param context
     * @param uid
     * @param list
     */
    public static void addSearchRecommendLabel(Context context, String uid, List<BookInfo> list) {
        if (list == null) {
            Log4an.e(TAG, "添加搜索推荐标签信息 list is null");
            return;
        }
        addPageCacheInfo(context, uid, PAGE_BOOKSEARCH, BOOKSEARCH_CHILD_RECOMMEND,
                BOOKSEARCH_CHILD_RECOMMEND_BOOK_LABEL, list);
    }

    /**
     * 获取搜索排行缓存书籍信息
     * 
     * @param context
     * @param uid
     * @return
     */
    public static List<BookInfo> getSearchRankBookInfo(Context context, String uid) {
        List<BookInfo> list =
                getPageCacheInfo(context, uid, PAGE_BOOKSEARCH, BOOKSEARCH_CHILD_RANK,
                        BOOKSEARCH_CHILD_RANK_BOOK_INFO);
        return list;
    }

    /**
     * 添加搜索排行缓存书籍信息
     * 
     * @param context
     * @param uid
     * @param list
     */
    public static void addSearchRankBookInfo(Context context, String uid, List<BookInfo> list) {
        if (list == null) {
            Log4an.e(TAG, "添加搜索排行缓存书籍信息 list is null");
            return;
        }
        addPageCacheInfo(context, uid, PAGE_BOOKSEARCH, BOOKSEARCH_CHILD_RANK,
                BOOKSEARCH_CHILD_RANK_BOOK_INFO, list);
    }

    /***************************** 书城推荐页面相关缓存 *********************/
    /**
     * 获取书城推荐页大图
     * 
     * @param context
     * @param uid
     * @return
     */
    public static List<BookInfo> getSquareRecommendImgs(Context context, String uid) {
        List<BookInfo> list =
                getPageCacheInfo(context, uid, PAGE_BOOKSQUARE, BOOKSQUARE_CHILD_RECOMMEND,
                        BOOKSQUARE_CHILD_RECOMMEND_IMGS);
        return list;
    }

    /**
     * 添加书城推荐页大图
     * 
     * @param context
     * @param uid
     * @param list
     */
    public static void addSquareRecommendImgs(Context context, String uid, List<BookInfo> list) {
        if (list == null) {
            Log4an.e(TAG, "添加搜索排行缓存书籍信息 list is null");
            return;
        }
        addPageCacheInfo(context, uid, PAGE_BOOKSQUARE, BOOKSQUARE_CHILD_RECOMMEND,
                BOOKSQUARE_CHILD_RECOMMEND_IMGS, list);
    }

    /**
     * 获取书城推荐页书籍信息
     * 
     * @param context
     * @param uid
     * @return
     */
    public static List<BookInfo> getSquareRecommendBookInfo(Context context, String uid) {
        List<BookInfo> list =
                getPageCacheInfo(context, uid, PAGE_BOOKSQUARE, BOOKSQUARE_CHILD_RECOMMEND,
                        BOOKSQUARE_CHILD_RECOMMEND_BOOKINFO);
        return list;
    }

    /**
     * 添加书城推荐页书籍信息
     * 
     * @param context
     * @param uid
     * @param list
     * @return
     */
    public static void addSquareRecommendBookInfo(Context context, String uid, List<BookInfo> list) {
        if (list == null) {
            Log4an.e(TAG, "添加书城推荐页书籍信息 list is null");
            return;
        }
        addPageCacheInfo(context, uid, PAGE_BOOKSQUARE, BOOKSQUARE_CHILD_RECOMMEND,
                BOOKSQUARE_CHILD_RECOMMEND_BOOKINFO, list);
    }

    /***************************** 书城排行页面相关缓存 *********************/
    /**
     * 获取书城排行书籍信息
     * 
     * @param context
     * @param uid
     * @return
     */
    public static List<BookInfo> getSquareRankInfo(Context context, String uid) {
        List<BookInfo> list =
                getPageCacheInfo(context, uid, PAGE_BOOKSQUARE, BOOKSQUARE_CHILD_RANK,
                        BOOKSQUARE_CHILD_RANK_BOOKINFO);
        return list;
    }

    /**
     * 添加书城排行书籍信息
     * 
     * @param context
     * @param uid
     * @param list
     */
    public static void addSquareRankInfo(Context context, String uid, List<BookInfo> list) {
        if (list == null) {
            Log4an.e(TAG, "添加书城排行书籍信息 list is null");
            return;
        }
        addPageCacheInfo(context, uid, PAGE_BOOKSQUARE, BOOKSQUARE_CHILD_RANK,
                BOOKSQUARE_CHILD_RANK_BOOKINFO, list);
    }

    /**
     * 获取书城排行书籍信息
     * 
     * @param context
     * @param uid
     * @return
     */
    public static List<BookInfo> getSquareRankLabel(Context context, String uid) {
        List<BookInfo> list =
                getPageCacheInfo(context, uid, PAGE_BOOKSQUARE, BOOKSQUARE_CHILD_RANK,
                        BOOKSQUARE_CHILD_RANK_BOOKLABEL);
        return list;
    }

    /**
     * 添加书城排行标签信息
     * 
     * @param context
     * @param uid
     * @param list
     */
    public static void addSquareRankLabel(Context context, String uid, List<BookInfo> list) {
        if (list == null) {
            Log4an.e(TAG, "添加书城排行标签信息 list is null");
            return;
        }
        addPageCacheInfo(context, uid, PAGE_BOOKSQUARE, BOOKSQUARE_CHILD_RANK,
                BOOKSQUARE_CHILD_RANK_BOOKLABEL, list);
    }

    /***************************** 书城分类页面相关缓存 *********************/
    /**
     * 获取书城分类相关缓存
     * 
     * @param context
     * @param uid
     * @return
     */
    public static List<BookInfo> getSquareSort(Context context, String uid) {
        List<BookInfo> list =
                getPageCacheInfo(context, uid, PAGE_BOOKSQUARE, BOOKSQUARE_CHILD_SORT,
                        BOOKSQUARE_CHILD_SORT_BOOKINFO);
        return list;
    }

    /**
     * 添加书城分类相关缓存
     * 
     * @param context
     * @param uid
     * @param list
     */
    public static void addSquareSort(Context context, String uid, List<BookInfo> list) {
        if (list == null) {
            Log4an.e(TAG, "添加书城分类相关缓存 list is null");
            return;
        }
        addPageCacheInfo(context, uid, PAGE_BOOKSQUARE, BOOKSQUARE_CHILD_SORT,
                BOOKSQUARE_CHILD_SORT_BOOKINFO, list);
    }

    /***************************** 书城限免页面相关缓存 *********************/
    /**
     * 获取书城限免相关缓存
     * 
     * @param context
     * @param uid
     * @return
     */
    public static List<BookInfo> getSquareFree(Context context, String uid) {
        List<BookInfo> list =
                getPageCacheInfo(context, uid, PAGE_BOOKSQUARE, BOOKSQUARE_CHILD_FREE,
                        BOOKSQUARE_CHILD_FREE_BOOKINFO);
        return list;
    }

    /**
     * 添加书城限免相关缓存
     * 
     * @param context
     * @param uid
     * @param list
     */
    public static void addSquareFree(Context context, String uid, List<BookInfo> list) {
        if (list == null) {
            Log4an.e(TAG, "添加书城限免相关缓存 list is null");
            return;
        }
        addPageCacheInfo(context, uid, PAGE_BOOKSQUARE, BOOKSQUARE_CHILD_FREE,
                BOOKSQUARE_CHILD_FREE_BOOKINFO, list);
    }

    /**
     * 获取缓存信息
     * 
     * @param context
     * @param uid
     * @param page 页面
     * @param pageType 页面的子页面类型
     * @param itemType 缓存详细类型
     * @return
     */
    private static List<BookInfo> getPageCacheInfo(Context context, String uid, String page,
            String pageType, String itemType) {
        if (context == null) {
            Log4an.e(TAG, "获取缓存信息失败 context=null");
            return null;
        }
        uid = TextUtils.isEmpty(uid) ? Constant.GUEST_USER_ID : uid;
        NewLocalDatabase database = NewLocalDatabase.getInstance(context);
        SQLiteDatabase db = null;
        List<BookInfo> infos = null;
        BookInfo info = null;
        Cursor cursor = null;
        try {
            db = database.getWritableDatabase(DatabasePassword.getPassWord());
            db.beginTransaction();
            // 获取旧的数据,不存在返回null
            cursor =
                    db.rawQuery(
                            "select * from book_page_cache where account=? and page=? and page_type=? and item_type=?",
                            new String[] {uid, page, pageType, itemType});
            if (cursor.getCount() > 0) {
                infos = new ArrayList<BookInfo>();
                cursor.moveToFirst();
                while (!cursor.isAfterLast()) {
                    info = new BookInfo();
                    info.setUserId(uid);
                    info.setBookId(cursor.getString(cursor.getColumnIndex("book_id")));
                    info.setSourceId(cursor.getString(cursor.getColumnIndex("source_id")));
                    info.setBookAuthorName(cursor.getString(cursor.getColumnIndex("author_name")));
                    info.setBookName(cursor.getString(cursor.getColumnIndex("book_name")));
                    info.setBookDownCount(cursor.getInt(cursor.getColumnIndex("down_count")));
                    info.setBookCoverImgUrl(cursor.getString(cursor.getColumnIndex("img_url")));
                    info.setBookMaxOid(cursor.getInt(cursor.getColumnIndex("oid_max")));
                    info.setBookPayState(cursor.getInt(cursor.getColumnIndex("paid")));
                    info.setBookPayMode(cursor.getInt(cursor.getColumnIndex("pay_mode")));
                    info.setBookPrice(cursor.getFloat(cursor.getColumnIndex("price")));
                    info.setBookWordCount(cursor.getString(cursor.getColumnIndex("word_count")));
                    info.setBookUpdateTime(cursor.getLong(cursor.getColumnIndex("info_update_time")));
                    info.setBookStatus(cursor.getString(cursor.getColumnIndex("status")));
                    info.setBookIntro(cursor.getString(cursor.getColumnIndex("intro")));
                    info.setBookHistoryState(cursor.getInt(cursor.getColumnIndex("in_history")));
                    info.setDiscount(cursor.getString(cursor.getColumnIndex("discount")));
//                    info.setBookHideStatecursor.getString(cursor.getColumnIndex("hide")));
                    info.setCoverHideState(cursor.getInt(cursor
                            .getColumnIndex("cr_cover_isopen")));
//                    info.setPage(cursor.getString(cursor.getColumnIndex("page")));
//                    info.setPageType(cursor.getString(cursor.getColumnIndex("page_type")));
//                    info.setItemType(cursor.getString(cursor.getColumnIndex("item_type")));
                    info.setBookType(cursor.getString(cursor.getColumnIndex("book_type")));

                    infos.add(info);
                    cursor.moveToNext();
                }
                db.setTransactionSuccessful();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
                cursor.close();
            }
            if (db != null && db.isOpen()) {
                db.close();
            }
        }
        return infos;

    }

    /**
     * 加入缓存
     * 
     * @param context
     * @param uid
     * @param page 页面
     * @param pageType 页面的子页面类型
     * @param itemType 缓存详细类型
     * @return
     */
    private static boolean addPageCacheInfo(Context context, String uid, String page,
            String pageType, String itemType, List<BookInfo> list) {
        if (context == null) {
            Log4an.e(TAG, "加入缓存信息失败 context=null");
            return false;
        }
        uid = TextUtils.isEmpty(uid) ? Constant.GUEST_USER_ID : uid;
        NewLocalDatabase database = NewLocalDatabase.getInstance(context);
        SQLiteDatabase db = null;
        BookInfo info = null;
        // 清除缓存
        delPageCacheInfo(context, uid, page, pageType, itemType);
        try {
            db = database.getWritableDatabase(DatabasePassword.getPassWord());
            db.beginTransaction();
            for (int i = 0; i < list.size(); i++) {
                info = list.get(i);
                ContentValues values = new ContentValues();
                values.put("author_name", info.getBookAuthorName());
                values.put("book_id", info.getBookId());
                values.put("source_id", info.getSourceId());
                values.put("book_name", info.getBookName());
                values.put("paid", info.getBookPayState());
                values.put("img_url", info.getBookCoverImgUrl());
                values.put("pay_mode", info.getBookPayMode());
                values.put("price", info.getBookPrice());
                values.put("account", uid);
                values.put("word_count", info.getBookWordCount());
                values.put("down_count", info.getBookDownCount());
                values.put("oid_max", info.getBookMaxOid());
                values.put("info_update_time", info.getBookUpdateTime());
                values.put("status", info.getBookStatus());
                values.put("intro", info.getBookIntro());
                values.put("in_history", info.getBookHistoryState());
                values.put("discount", info.getDiscount());
                values.put("hide", info.getBookHideState());
                values.put("cr_cover_isopen", info.getCoverHideState());
                values.put("page", page);
                values.put("page_type", pageType);
                values.put("item_type", itemType);
                values.put("book_type", info.getBookType());
                db.insert("book_page_cache", null, values);
            }
            db.setTransactionSuccessful();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (db != null && db.isOpen()) {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
                db.close();
            }
        }
        return false;
    }

    /**
     * 删除缓存
     * 
     * @param context
     * @param uid
     * @param page 页面
     * @param pageType 页面的子页面类型
     * @param itemType 缓存详细类型
     * @return
     */
    private static int delPageCacheInfo(Context context, String uid, String page, String pageType,
            String itemType) {
        if (context == null) {
            Log4an.e(TAG, "删除缓存信息失败 context=null");
            return -1;
        }
        uid = TextUtils.isEmpty(uid) ? Constant.GUEST_USER_ID : uid;
        NewLocalDatabase database = NewLocalDatabase.getInstance(context);
        SQLiteDatabase db = null;
        try {
            db = database.getWritableDatabase(DatabasePassword.getPassWord());
            db.beginTransaction();
            int delete =
                    db.delete("book_page_cache",
                            "account=? and page=? and page_type=? and item_type=?", new String[] {
                                    uid, page, pageType, itemType});
            db.setTransactionSuccessful();
            return delete;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (db != null && db.isOpen()) {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
                db.close();
            }
        }
        return -1;

    }
}
